<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>添加用户</title>
    <!-- 引入Bootstrap CSS -->
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h1>添加新用户</h1>
    <form id="addUserForm">
        <div class="form-group">
            <label for="userName">用户名</label>
            <input type="text" id="userName" name="userName" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="userEmail">邮箱</label>
            <input type="email" id="userEmail" name="userEmail" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="userPassword">密码</label>
            <input type="password" id="userPassword" name="userPassword" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-success">保存</button>
        <a href="/userManage" class="btn btn-secondary">返回列表</a>
    </form>
    </div>

    <!-- JavaScript部分用于AJAX提交 -->
    <script>
document.getElementById('addUserForm').onsubmit = function(event) {
    event.preventDefault(); // 防止默认的表单提交行为

    var user = {
        userName: document.getElementById('userName').value,
        userEmail: document.getElementById('userEmail').value,
        userPassword: document.getElementById('userPassword').value // 添加用户密码
    };

    fetch('/user', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(user),
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(errorData => { throw new Error(JSON.stringify(errorData.data)); });
<!--            return response.json().then(errorData => { throw new Error(errorData.message || "添加用户失败"); });-->
        }
        return response.json();
    })
    .then(data => {
        alert("用户添加成功");
        window.location.href = "/userManage"; // 成功后重定向到用户管理页面
    })
    .catch((error) => {
        console.error('Error:', error);
        alert(error.message); // 显示具体的错误信息
    });
};
</script>

    <!-- Bootstrap JS and dependencies (可选) -->
<script src="/static/js/jquery-3.5.1.slim.min.js"></script>
<script src="/static//js/popper.min.js"></script>
<script src="/static//js/bootstrap.min.js"></script>
</body>
</html>